package com.gz.dao;

import com.gz.utils.JdbcUtilsByDruid;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public class BasicDao<T>{//泛型指定具体类型

    private QueryRunner queryRunner = new QueryRunner();

    //开发通用的dml方法，针对任意表
    public  int update(String sql,Object... parameters){

        Connection conn = null;

        try {
            conn= JdbcUtilsByDruid.getConnection();
            int update = queryRunner.update(conn, sql, parameters);
            return update;
        } catch (SQLException e) {
            throw new RuntimeException(e);//将编译异常变为运行异常，抛出
        } finally {
            JdbcUtilsByDruid.close(null,null,conn);
        }
    }

    //返回多个T对象(即查询结果是多行的),针对任意表
    /**
     *
     * @param sql sql语句，可以有?
     * @param clazz(一般写成这样) 传入一个类的Class对象 比如 Table.class
     * @param parameters 传入问号的具体的值，可以是多个，如多个问号，传多个值
     * @return 根据Table.class 返回对应的ArrayList集合
     */
    public List<T> queryMulti(String sql, Class<T> clazz,Object... parameters){
        Connection conn = null;

        try {
            conn= JdbcUtilsByDruid.getConnection();
            return queryRunner.query(conn,sql,new BeanListHandler<T>(clazz),parameters);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            JdbcUtilsByDruid.close(null,null,conn);
        }
    }

    //返回单行的查询结果
    public T querySingle(String sql, Class<T> clazz,Object... parameters){
        Connection conn = null;

        try {
            conn= JdbcUtilsByDruid.getConnection();
            return queryRunner.query(conn,sql,new BeanHandler<T>(clazz),parameters);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            JdbcUtilsByDruid.close(null,null,conn);
        }
    }

    //查询单行单列，即返回单值的方法
    public Object queryScalar(String sql, Object... parameters){
        Connection conn = null;

        try {
            conn= JdbcUtilsByDruid.getConnection();
            return queryRunner.query(conn,sql,new ScalarHandler<>(),parameters);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            JdbcUtilsByDruid.close(null,null,conn);
        }
    }

}
